home *** CD-ROM | disk | FTP | other *** search
/ Freelog 115 / FreelogNo115-MaiJuin2013.iso / Internet / AvantBrowser / asetup.exe / _data / webkit / resources.pak / Unnamed File 000063.txt < prev    next >
Text File  |  2013-04-03  |  41KB  |  1,278 lines

  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4.  
  5. // require: array_data_model.js
  6. // require: list_selection_model.js
  7. // require: list_selection_controller.js
  8. // require: list_item.js
  9.  
  10. /**
  11.  * @fileoverview This implements a list control.
  12.  */
  13.  
  14. cr.define('cr.ui', function() {
  15.   /** @const */ var ListSelectionModel = cr.ui.ListSelectionModel;
  16.   /** @const */ var ListSelectionController = cr.ui.ListSelectionController;
  17.   /** @const */ var ArrayDataModel = cr.ui.ArrayDataModel;
  18.  
  19.   /**
  20.    * Whether a mouse event is inside the element viewport. This will return
  21.    * false if the mouseevent was generated over a border or a scrollbar.
  22.    * @param {!HTMLElement} el The element to test the event with.
  23.    * @param {!Event} e The mouse event.
  24.    * @param {boolean} Whether the mouse event was inside the viewport.
  25.    */
  26.   function inViewport(el, e) {
  27.     var rect = el.getBoundingClientRect();
  28.     var x = e.clientX;
  29.     var y = e.clientY;
  30.     return x >= rect.left + el.clientLeft &&
  31.            x < rect.left + el.clientLeft + el.clientWidth &&
  32.            y >= rect.top + el.clientTop &&
  33.            y < rect.top + el.clientTop + el.clientHeight;
  34.   }
  35.  
  36.   function getComputedStyle(el) {
  37.     return el.ownerDocument.defaultView.getComputedStyle(el);
  38.   }
  39.  
  40.   /**
  41.    * Creates a new list element.
  42.    * @param {Object=} opt_propertyBag Optional properties.
  43.    * @constructor
  44.    * @extends {HTMLUListElement}
  45.    */
  46.   var List = cr.ui.define('list');
  47.  
  48.   List.prototype = {
  49.     __proto__: HTMLUListElement.prototype,
  50.  
  51.     /**
  52.      * Measured size of list items. This is lazily calculated the first time it
  53.      * is needed. Note that lead item is allowed to have a different height, to
  54.      * accommodate lists where a single item at a time can be expanded to show
  55.      * more detail.
  56.      * @type {{height: number, marginTop: number, marginBottom:number,
  57.      *     width: number, marginLeft: number, marginRight:number}}
  58.      * @private
  59.      */
  60.     measured_: undefined,
  61.  
  62.     /**
  63.      * Whether or not the list is autoexpanding. If true, the list resizes
  64.      * its height to accomadate all children.
  65.      * @type {boolean}
  66.      * @private
  67.      */
  68.     autoExpands_: false,
  69.  
  70.     /**
  71.      * Whether or not the rows on list have various heights. If true, all the
  72.      * rows have the same fixed height. Otherwise, each row resizes its height
  73.      * to accommodate all contents.
  74.      * @type {boolean}
  75.      * @private
  76.      */
  77.     fixedHeight_: true,
  78.  
  79.     /**
  80.      * Whether or not the list view has a blank space below the last row.
  81.      * @type {boolean}
  82.      * @private
  83.      */
  84.     remainingSpace_: true,
  85.  
  86.     /**
  87.      * Function used to create grid items.
  88.      * @type {function(): !ListItem}
  89.      * @private
  90.      */
  91.     itemConstructor_: cr.ui.ListItem,
  92.  
  93.     /**
  94.      * Function used to create grid items.
  95.      * @type {function(): !ListItem}
  96.      */
  97.     get itemConstructor() {
  98.       return this.itemConstructor_;
  99.     },
  100.     set itemConstructor(func) {
  101.       if (func != this.itemConstructor_) {
  102.         this.itemConstructor_ = func;
  103.         this.cachedItems_ = {};
  104.         this.redraw();
  105.       }
  106.     },
  107.  
  108.     dataModel_: null,
  109.  
  110.     /**
  111.      * The data model driving the list.
  112.      * @type {ArrayDataModel}
  113.      */
  114.     set dataModel(dataModel) {
  115.       if (this.dataModel_ != dataModel) {
  116.         if (!this.boundHandleDataModelPermuted_) {
  117.           this.boundHandleDataModelPermuted_ =
  118.               this.handleDataModelPermuted_.bind(this);
  119.           this.boundHandleDataModelChange_ =
  120.               this.handleDataModelChange_.bind(this);
  121.         }
  122.  
  123.         if (this.dataModel_) {
  124.           this.dataModel_.removeEventListener(
  125.               'permuted',
  126.               this.boundHandleDataModelPermuted_);
  127.           this.dataModel_.removeEventListener('change',
  128.                                               this.boundHandleDataModelChange_);
  129.         }
  130.  
  131.         this.dataModel_ = dataModel;
  132.  
  133.         this.cachedItems_ = {};
  134.         this.cachedItemHeights_ = {};
  135.         this.selectionModel.clear();
  136.         if (dataModel)
  137.           this.selectionModel.adjustLength(dataModel.length);
  138.  
  139.         if (this.dataModel_) {
  140.           this.dataModel_.addEventListener(
  141.               'permuted',
  142.               this.boundHandleDataModelPermuted_);
  143.           this.dataModel_.addEventListener('change',
  144.                                            this.boundHandleDataModelChange_);
  145.         }
  146.  
  147.         this.redraw();
  148.       }
  149.     },
  150.  
  151.     get dataModel() {
  152.       return this.dataModel_;
  153.     },
  154.  
  155.  
  156.     /**
  157.      * Cached item for measuring the default item size by measureItem().
  158.      * @type {ListItem}
  159.      */
  160.     cachedMeasuredItem_: null,
  161.  
  162.     /**
  163.      * The selection model to use.
  164.      * @type {cr.ui.ListSelectionModel}
  165.      */
  166.     get selectionModel() {
  167.       return this.selectionModel_;
  168.     },
  169.     set selectionModel(sm) {
  170.       var oldSm = this.selectionModel_;
  171.       if (oldSm == sm)
  172.         return;
  173.  
  174.       if (!this.boundHandleOnChange_) {
  175.         this.boundHandleOnChange_ = this.handleOnChange_.bind(this);
  176.         this.boundHandleLeadChange_ = this.handleLeadChange_.bind(this);
  177.       }
  178.  
  179.       if (oldSm) {
  180.         oldSm.removeEventListener('change', this.boundHandleOnChange_);
  181.         oldSm.removeEventListener('leadIndexChange',
  182.                                   this.boundHandleLeadChange_);
  183.       }
  184.  
  185.       this.selectionModel_ = sm;
  186.       this.selectionController_ = this.createSelectionController(sm);
  187.  
  188.       if (sm) {
  189.         sm.addEventListener('change', this.boundHandleOnChange_);
  190.         sm.addEventListener('leadIndexChange', this.boundHandleLeadChange_);
  191.       }
  192.     },
  193.  
  194.     /**
  195.      * Whether or not the list auto-expands.
  196.      * @type {boolean}
  197.      */
  198.     get autoExpands() {
  199.       return this.autoExpands_;
  200.     },
  201.     set autoExpands(autoExpands) {
  202.       if (this.autoExpands_ == autoExpands)
  203.         return;
  204.       this.autoExpands_ = autoExpands;
  205.       this.redraw();
  206.     },
  207.  
  208.     /**
  209.      * Whether or not the rows on list have various heights.
  210.      * @type {boolean}
  211.      */
  212.     get fixedHeight() {
  213.       return this.fixedHeight_;
  214.     },
  215.     set fixedHeight(fixedHeight) {
  216.       if (this.fixedHeight_ == fixedHeight)
  217.         return;
  218.       this.fixedHeight_ = fixedHeight;
  219.       this.redraw();
  220.     },
  221.  
  222.     /**
  223.      * Convenience alias for selectionModel.selectedItem
  224.      * @type {*}
  225.      */
  226.     get selectedItem() {
  227.       var dataModel = this.dataModel;
  228.       if (dataModel) {
  229.         var index = this.selectionModel.selectedIndex;
  230.         if (index != -1)
  231.           return dataModel.item(index);
  232.       }
  233.       return null;
  234.     },
  235.     set selectedItem(selectedItem) {
  236.       var dataModel = this.dataModel;
  237.       if (dataModel) {
  238.         var index = this.dataModel.indexOf(selectedItem);
  239.         this.selectionModel.selectedIndex = index;
  240.       }
  241.     },
  242.  
  243.     /**
  244.      * Convenience alias for selectionModel.selectedItems
  245.      * @type {!Array<*>}
  246.      */
  247.     get selectedItems() {
  248.       var indexes = this.selectionModel.selectedIndexes;
  249.       var dataModel = this.dataModel;
  250.       if (dataModel) {
  251.         return indexes.map(function(i) {
  252.           return dataModel.item(i);
  253.         });
  254.       }
  255.       return [];
  256.     },
  257.  
  258.     /**
  259.      * The HTML elements representing the items.
  260.      * @type {HTMLCollection}
  261.      */
  262.     get items() {
  263.       return Array.prototype.filter.call(this.children,
  264.                                          this.isItem, this);
  265.     },
  266.  
  267.     /**
  268.      * Returns true if the child is a list item. Subclasses may override this
  269.      * to filter out certain elements.
  270.      * @param {Node} child Child of the list.
  271.      * @return {boolean} True if a list item.
  272.      */
  273.     isItem: function(child) {
  274.       return child.nodeType == Node.ELEMENT_NODE &&
  275.              child != this.beforeFiller_ && child != this.afterFiller_;
  276.     },
  277.  
  278.     batchCount_: 0,
  279.  
  280.     /**
  281.      * When making a lot of updates to the list, the code could be wrapped in
  282.      * the startBatchUpdates and finishBatchUpdates to increase performance. Be
  283.      * sure that the code will not return without calling endBatchUpdates or the
  284.      * list will not be correctly updated.
  285.      */
  286.     startBatchUpdates: function() {
  287.       this.batchCount_++;
  288.     },
  289.  
  290.     /**
  291.      * See startBatchUpdates.
  292.      */
  293.     endBatchUpdates: function() {
  294.       this.batchCount_--;
  295.       if (this.batchCount_ == 0)
  296.         this.redraw();
  297.     },
  298.  
  299.     /**
  300.      * Initializes the element.
  301.      */
  302.     decorate: function() {
  303.       // Add fillers.
  304.       this.beforeFiller_ = this.ownerDocument.createElement('div');
  305.       this.afterFiller_ = this.ownerDocument.createElement('div');
  306.       this.beforeFiller_.className = 'spacer';
  307.       this.afterFiller_.className = 'spacer';
  308.       this.textContent = '';
  309.       this.appendChild(this.beforeFiller_);
  310.       this.appendChild(this.afterFiller_);
  311.  
  312.       var length = this.dataModel ? this.dataModel.length : 0;
  313.       this.selectionModel = new ListSelectionModel(length);
  314.  
  315.       this.addEventListener('dblclick', this.handleDoubleClick_);
  316.       this.addEventListener('mousedown', this.handlePointerDownUp_);
  317.       this.addEventListener('mouseup', this.handlePointerDownUp_);
  318.       this.addEventListener('keydown', this.handleKeyDown);
  319.       this.addEventListener('focus', this.handleElementFocus_, true);
  320.       this.addEventListener('blur', this.handleElementBlur_, true);
  321.       this.addEventListener('scroll', this.handleScroll.bind(this));
  322.       this.setAttribute('role', 'list');
  323.  
  324.       // Make list focusable
  325.       if (!this.hasAttribute('tabindex'))
  326.         this.tabIndex = 0;
  327.  
  328.       // Try to get an unique id prefix from the id of this element or the
  329.       // nearest ancestor with an id.
  330.       var element = this;
  331.       while (element && !element.id)
  332.         element = element.parentElement;
  333.       if (element && element.id)
  334.         this.uniqueIdPrefix_ = element.id;
  335.       else
  336.         this.uniqueIdPrefix_ = 'list';
  337.  
  338.       // The next id suffix to use when giving each item an unique id.
  339.       this.nextUniqueIdSuffix_ = 0;
  340.     },
  341.  
  342.     /**
  343.      * @param {ListItem=} item The list item to measure.
  344.      * @return {number} The height of the given item. If the fixed height on CSS
  345.      * is set by 'px', uses that value as height. Otherwise, measures the size.
  346.      * @private
  347.      */
  348.     measureItemHeight_: function(item) {
  349.       return this.measureItem(item).height;
  350.     },
  351.  
  352.     /**
  353.      * @return {number} The height of default item, measuring it if necessary.
  354.      * @private
  355.      */
  356.     getDefaultItemHeight_: function() {
  357.       return this.getDefaultItemSize_().height;
  358.     },
  359.  
  360.     /**
  361.      * @param {number} index The index of the item.
  362.      * @return {number} The height of the item, measuring it if necessary.
  363.      */
  364.     getItemHeightByIndex_: function(index) {
  365.       // If |this.fixedHeight_| is true, all the rows have same default height.
  366.       if (this.fixedHeight_)
  367.         return this.getDefaultItemHeight_();
  368.  
  369.       if (this.cachedItemHeights_[index])
  370.         return this.cachedItemHeights_[index];
  371.  
  372.       var item = this.getListItemByIndex(index);
  373.       if (item) {
  374.         var h = this.measureItemHeight_(item);
  375.         this.cachedItemHeights_[index] = h;
  376.         return h;
  377.       }
  378.       return this.getDefaultItemHeight_();
  379.     },
  380.  
  381.     /**
  382.      * @return {{height: number, width: number}} The height and width
  383.      *     of default item, measuring it if necessary.
  384.      * @private
  385.      */
  386.     getDefaultItemSize_: function() {
  387.       if (!this.measured_ || !this.measured_.height) {
  388.         this.measured_ = this.measureItem();
  389.       }
  390.       return this.measured_;
  391.     },
  392.  
  393.     /**
  394.      * Creates an item (dataModel.item(0)) and measures its height. The item is
  395.      * cached instead of creating a new one every time..
  396.      * @param {ListItem=} opt_item The list item to use to do the measuring. If
  397.      *     this is not provided an item will be created based on the first value
  398.      *     in the model.
  399.      * @return {{height: number, marginTop: number, marginBottom:number,
  400.      *     width: number, marginLeft: number, marginRight:number}}
  401.      *     The height and width of the item, taking
  402.      *     margins into account, and the top, bottom, left and right margins
  403.      *     themselves.
  404.      */
  405.     measureItem: function(opt_item) {
  406.       var dataModel = this.dataModel;
  407.       if (!dataModel || !dataModel.length)
  408.         return 0;
  409.       var item = opt_item || this.cachedMeasuredItem_ ||
  410.           this.createItem(dataModel.item(0));
  411.       if (!opt_item) {
  412.         this.cachedMeasuredItem_ = item;
  413.         this.appendChild(item);
  414.       }
  415.  
  416.       var rect = item.getBoundingClientRect();
  417.       var cs = getComputedStyle(item);
  418.       var mt = parseFloat(cs.marginTop);
  419.       var mb = parseFloat(cs.marginBottom);
  420.       var ml = parseFloat(cs.marginLeft);
  421.       var mr = parseFloat(cs.marginRight);
  422.       var h = rect.height;
  423.       var w = rect.width;
  424.       var mh = 0;
  425.       var mv = 0;
  426.  
  427.       // Handle margin collapsing.
  428.       if (mt < 0 && mb < 0) {
  429.         mv = Math.min(mt, mb);
  430.       } else if (mt >= 0 && mb >= 0) {
  431.         mv = Math.max(mt, mb);
  432.       } else {
  433.         mv = mt + mb;
  434.       }
  435.       h += mv;
  436.  
  437.       if (ml < 0 && mr < 0) {
  438.         mh = Math.min(ml, mr);
  439.       } else if (ml >= 0 && mr >= 0) {
  440.         mh = Math.max(ml, mr);
  441.       } else {
  442.         mh = ml + mr;
  443.       }
  444.       w += mh;
  445.  
  446.       if (!opt_item)
  447.         this.removeChild(item);
  448.       return {
  449.           height: Math.max(0, h),
  450.           marginTop: mt, marginBottom: mb,
  451.           width: Math.max(0, w),
  452.           marginLeft: ml, marginRight: mr};
  453.     },
  454.  
  455.     /**
  456.      * Callback for the double click event.
  457.      * @param {Event} e The mouse event object.
  458.      * @private
  459.      */
  460.     handleDoubleClick_: function(e) {
  461.       if (this.disabled)
  462.         return;
  463.  
  464.       var target = e.target;
  465.  
  466.       target = this.getListItemAncestor(target);
  467.       if (target)
  468.         this.activateItemAtIndex(this.getIndexOfListItem(target));
  469.     },
  470.  
  471.     /**
  472.      * Callback for mousedown and mouseup events.
  473.      * @param {Event} e The mouse event object.
  474.      * @private
  475.      */
  476.     handlePointerDownUp_: function(e) {
  477.       if (this.disabled)
  478.         return;
  479.  
  480.       var target = e.target;
  481.  
  482.       // If the target was this element we need to make sure that the user did
  483.       // not click on a border or a scrollbar.
  484.       if (target == this) {
  485.         if (inViewport(target, e))
  486.           this.selectionController_.handlePointerDownUp(e, -1);
  487.         return;
  488.       }
  489.  
  490.       target = this.getListItemAncestor(target);
  491.  
  492.       var index = this.getIndexOfListItem(target);
  493.       this.selectionController_.handlePointerDownUp(e, index);
  494.     },
  495.  
  496.     /**
  497.      * Called when an element in the list is focused. Marks the list as having
  498.      * a focused element, and dispatches an event if it didn't have focus.
  499.      * @param {Event} e The focus event.
  500.      * @private
  501.      */
  502.     handleElementFocus_: function(e) {
  503.       if (!this.hasElementFocus)
  504.         this.hasElementFocus = true;
  505.     },
  506.  
  507.     /**
  508.      * Called when an element in the list is blurred. If focus moves outside
  509.      * the list, marks the list as no longer having focus and dispatches an
  510.      * event.
  511.      * @param {Event} e The blur event.
  512.      * @private
  513.      */
  514.     handleElementBlur_: function(e) {
  515.       // When the blur event happens we do not know who is getting focus so we
  516.       // delay this a bit until we know if the new focus node is outside the
  517.       // list.
  518.       var list = this;
  519.       var doc = e.target.ownerDocument;
  520.       window.setTimeout(function() {
  521.         var activeElement = doc.activeElement;
  522.         if (!list.contains(activeElement))
  523.           list.hasElementFocus = false;
  524.       });
  525.     },
  526.  
  527.     /**
  528.      * Returns the list item element containing the given element, or null if
  529.      * it doesn't belong to any list item element.
  530.      * @param {HTMLElement} element The element.
  531.      * @return {ListItem} The list item containing |element|, or null.
  532.      */
  533.     getListItemAncestor: function(element) {
  534.       var container = element;
  535.       while (container && container.parentNode != this) {
  536.         container = container.parentNode;
  537.       }
  538.       return container;
  539.     },
  540.  
  541.     /**
  542.      * Handle a keydown event.
  543.      * @param {Event} e The keydown event.
  544.      * @return {boolean} Whether the key event was handled.
  545.      */
  546.     handleKeyDown: function(e) {
  547.       if (this.disabled)
  548.         return;
  549.  
  550.       return this.selectionController_.handleKeyDown(e);
  551.     },
  552.  
  553.     scrollTopBefore_: 0,
  554.  
  555.     /**
  556.      * Handle a scroll event.
  557.      * @param {Event} e The scroll event.
  558.      */
  559.     handleScroll: function(e) {
  560.       var scrollTop = this.scrollTop;
  561.       if (scrollTop != this.scrollTopBefore_) {
  562.         this.scrollTopBefore_ = scrollTop;
  563.         this.redraw();
  564.       }
  565.     },
  566.  
  567.     /**
  568.      * Callback from the selection model. We dispatch {@code change} events
  569.      * when the selection changes.
  570.      * @param {!cr.Event} e Event with change info.
  571.      * @private
  572.      */
  573.     handleOnChange_: function(ce) {
  574.       ce.changes.forEach(function(change) {
  575.         var listItem = this.getListItemByIndex(change.index);
  576.         if (listItem) {
  577.           listItem.selected = change.selected;
  578.           if (change.selected) {
  579.             listItem.setAttribute('aria-posinset', change.index + 1);
  580.             listItem.setAttribute('aria-setsize', this.dataModel.length);
  581.             this.setAttribute('aria-activedescendant', listItem.id);
  582.           } else {
  583.             listItem.removeAttribute('aria-posinset');
  584.             listItem.removeAttribute('aria-setsize');
  585.           }
  586.         }
  587.       }, this);
  588.  
  589.       cr.dispatchSimpleEvent(this, 'change');
  590.     },
  591.  
  592.     /**
  593.      * Handles a change of the lead item from the selection model.
  594.      * @param {Event} pe The property change event.
  595.      * @private
  596.      */
  597.     handleLeadChange_: function(pe) {
  598.       var element;
  599.       if (pe.oldValue != -1) {
  600.         if ((element = this.getListItemByIndex(pe.oldValue)))
  601.           element.lead = false;
  602.       }
  603.  
  604.       if (pe.newValue != -1) {
  605.         if ((element = this.getListItemByIndex(pe.newValue)))
  606.           element.lead = true;
  607.         if (pe.oldValue != pe.newValue) {
  608.           this.scrollIndexIntoView(pe.newValue);
  609.           // If the lead item has a different height than other items, then we
  610.           // may run into a problem that requires a second attempt to scroll
  611.           // it into view. The first scroll attempt will trigger a redraw,
  612.           // which will clear out the list and repopulate it with new items.
  613.           // During the redraw, the list may shrink temporarily, which if the
  614.           // lead item is the last item, will move the scrollTop up since it
  615.           // cannot extend beyond the end of the list. (Sadly, being scrolled to
  616.           // the bottom of the list is not "sticky.") So, we set a timeout to
  617.           // rescroll the list after this all gets sorted out. This is perhaps
  618.           // not the most elegant solution, but no others seem obvious.
  619.           var self = this;
  620.           window.setTimeout(function() {
  621.             self.scrollIndexIntoView(pe.newValue);
  622.           });
  623.         }
  624.       }
  625.     },
  626.  
  627.     /**
  628.      * This handles data model 'permuted' event.
  629.      * this event is dispatched as a part of sort or splice.
  630.      * We need to
  631.      *  - adjust the cache.
  632.      *  - adjust selection.
  633.      *  - redraw. (called in this.endBatchUpdates())
  634.      *  It is important that the cache adjustment happens before selection model
  635.      *  adjustments.
  636.      * @param {Event} e The 'permuted' event.
  637.      */
  638.     handleDataModelPermuted_: function(e) {
  639.       var newCachedItems = {};
  640.       for (var index in this.cachedItems_) {
  641.         if (e.permutation[index] != -1) {
  642.           var newIndex = e.permutation[index];
  643.           newCachedItems[newIndex] = this.cachedItems_[index];
  644.           newCachedItems[newIndex].listIndex = newIndex;
  645.         }
  646.       }
  647.       this.cachedItems_ = newCachedItems;
  648.  
  649.       var newCachedItemHeights = {};
  650.       for (var index in this.cachedItemHeights_) {
  651.         if (e.permutation[index] != -1) {
  652.           newCachedItemHeights[e.permutation[index]] =
  653.               this.cachedItemHeights_[index];
  654.         }
  655.       }
  656.       this.cachedItemHeights_ = newCachedItemHeights;
  657.  
  658.       this.startBatchUpdates();
  659.  
  660.       var sm = this.selectionModel;
  661.       sm.adjustLength(e.newLength);
  662.       sm.adjustToReordering(e.permutation);
  663.  
  664.       this.endBatchUpdates();
  665.     },
  666.  
  667.     handleDataModelChange_: function(e) {
  668.       delete this.cachedItems_[e.index];
  669.       delete this.cachedItemHeights_[e.index];
  670.       this.cachedMeasuredItem_ = null;
  671.  
  672.       if (e.index >= this.firstIndex_ &&
  673.           (e.index < this.lastIndex_ || this.remainingSpace_)) {
  674.         this.redraw();
  675.       }
  676.     },
  677.  
  678.     /**
  679.      * @param {number} index The index of the item.
  680.      * @return {number} The top position of the item inside the list.
  681.      */
  682.     getItemTop: function(index) {
  683.       if (this.fixedHeight_) {
  684.         var itemHeight = this.getDefaultItemHeight_();
  685.         return index * itemHeight;
  686.       } else {
  687.         this.ensureAllItemSizesInCache();
  688.         var top = 0;
  689.         for (var i = 0; i < index; i++) {
  690.           top += this.getItemHeightByIndex_(i);
  691.         }
  692.         return top;
  693.       }
  694.     },
  695.  
  696.     /**
  697.      * @param {number} index The index of the item.
  698.      * @return {number} The row of the item. May vary in the case
  699.      *     of multiple columns.
  700.      */
  701.     getItemRow: function(index) {
  702.       return index;
  703.     },
  704.  
  705.     /**
  706.      * @param {number} row The row.
  707.      * @return {number} The index of the first item in the row.
  708.      */
  709.     getFirstItemInRow: function(row) {
  710.       return row;
  711.     },
  712.  
  713.     /**
  714.      * Ensures that a given index is inside the viewport.
  715.      * @param {number} index The index of the item to scroll into view.
  716.      * @return {boolean} Whether any scrolling was needed.
  717.      */
  718.     scrollIndexIntoView: function(index) {
  719.       var dataModel = this.dataModel;
  720.       if (!dataModel || index < 0 || index >= dataModel.length)
  721.         return false;
  722.  
  723.       var itemHeight = this.getItemHeightByIndex_(index);
  724.       var scrollTop = this.scrollTop;
  725.       var top = this.getItemTop(index);
  726.       var clientHeight = this.clientHeight;
  727.  
  728.       var self = this;
  729.       // Function to adjust the tops of viewport and row.
  730.       function scrollToAdjustTop() {
  731.           self.scrollTop = top;
  732.           return true;
  733.       };
  734.       // Function to adjust the bottoms of viewport and row.
  735.       function scrollToAdjustBottom() {
  736.           var cs = getComputedStyle(self);
  737.           var paddingY = parseInt(cs.paddingTop, 10) +
  738.                          parseInt(cs.paddingBottom, 10);
  739.  
  740.           if (top + itemHeight > scrollTop + clientHeight - paddingY) {
  741.             self.scrollTop = top + itemHeight - clientHeight + paddingY;
  742.             return true;
  743.           }
  744.           return false;
  745.       };
  746.  
  747.       // Check if the entire of given indexed row can be shown in the viewport.
  748.       if (itemHeight <= clientHeight) {
  749.         if (top < scrollTop)
  750.           return scrollToAdjustTop();
  751.         if (scrollTop + clientHeight < top + itemHeight)
  752.           return scrollToAdjustBottom();
  753.       } else {
  754.         if (scrollTop < top)
  755.           return scrollToAdjustTop();
  756.         if (top + itemHeight < scrollTop + clientHeight)
  757.           return scrollToAdjustBottom();
  758.       }
  759.       return false;
  760.     },
  761.  
  762.     /**
  763.      * @return {!ClientRect} The rect to use for the context menu.
  764.      */
  765.     getRectForContextMenu: function() {
  766.       // TODO(arv): Add trait support so we can share more code between trees
  767.       // and lists.
  768.       var index = this.selectionModel.selectedIndex;
  769.       var el = this.getListItemByIndex(index);
  770.       if (el)
  771.         return el.getBoundingClientRect();
  772.       return this.getBoundingClientRect();
  773.     },
  774.  
  775.     /**
  776.      * Takes a value from the data model and finds the associated list item.
  777.      * @param {*} value The value in the data model that we want to get the list
  778.      *     item for.
  779.      * @return {ListItem} The first found list item or null if not found.
  780.      */
  781.     getListItem: function(value) {
  782.       var dataModel = this.dataModel;
  783.       if (dataModel) {
  784.         var index = dataModel.indexOf(value);
  785.         return this.getListItemByIndex(index);
  786.       }
  787.       return null;
  788.     },
  789.  
  790.     /**
  791.      * Find the list item element at the given index.
  792.      * @param {number} index The index of the list item to get.
  793.      * @return {ListItem} The found list item or null if not found.
  794.      */
  795.     getListItemByIndex: function(index) {
  796.       return this.cachedItems_[index] || null;
  797.     },
  798.  
  799.     /**
  800.      * Find the index of the given list item element.
  801.      * @param {ListItem} item The list item to get the index of.
  802.      * @return {number} The index of the list item, or -1 if not found.
  803.      */
  804.     getIndexOfListItem: function(item) {
  805.       var index = item.listIndex;
  806.       if (this.cachedItems_[index] == item) {
  807.         return index;
  808.       }
  809.       return -1;
  810.     },
  811.  
  812.     /**
  813.      * Creates a new list item.
  814.      * @param {*} value The value to use for the item.
  815.      * @return {!ListItem} The newly created list item.
  816.      */
  817.     createItem: function(value) {
  818.       var item = new this.itemConstructor_(value);
  819.       item.label = value;
  820.       item.id = this.uniqueIdPrefix_ + '-' + this.nextUniqueIdSuffix_++;
  821.       if (typeof item.decorate == 'function')
  822.         item.decorate();
  823.       return item;
  824.     },
  825.  
  826.     /**
  827.      * Creates the selection controller to use internally.
  828.      * @param {cr.ui.ListSelectionModel} sm The underlying selection model.
  829.      * @return {!cr.ui.ListSelectionController} The newly created selection
  830.      *     controller.
  831.      */
  832.     createSelectionController: function(sm) {
  833.       return new ListSelectionController(sm);
  834.     },
  835.  
  836.     /**
  837.      * Return the heights (in pixels) of the top of the given item index within
  838.      * the list, and the height of the given item itself, accounting for the
  839.      * possibility that the lead item may be a different height.
  840.      * @param {number} index The index to find the top height of.
  841.      * @return {{top: number, height: number}} The heights for the given index.
  842.      * @private
  843.      */
  844.     getHeightsForIndex_: function(index) {
  845.       var itemHeight = this.getItemHeightByIndex_(index);
  846.       var top = this.getItemTop(index);
  847.       return {top: top, height: itemHeight};
  848.     },
  849.  
  850.     /**
  851.      * Find the index of the list item containing the given y offset (measured
  852.      * in pixels from the top) within the list. In the case of multiple columns,
  853.      * returns the first index in the row.
  854.      * @param {number} offset The y offset in pixels to get the index of.
  855.      * @return {number} The index of the list item. Returns the list size if
  856.      *     given offset exceeds the height of list.
  857.      * @private
  858.      */
  859.     getIndexForListOffset_: function(offset) {
  860.       var itemHeight = this.getDefaultItemHeight_();
  861.       if (!itemHeight)
  862.         return this.dataModel.length;
  863.  
  864.       if (this.fixedHeight_)
  865.         return this.getFirstItemInRow(Math.floor(offset / itemHeight));
  866.  
  867.       // If offset exceeds the height of list.
  868.       var lastHeight = 0;
  869.       if (this.dataModel.length) {
  870.         var h = this.getHeightsForIndex_(this.dataModel.length - 1);
  871.         lastHeight = h.top + h.height;
  872.       }
  873.       if (lastHeight < offset)
  874.         return this.dataModel.length;
  875.  
  876.       // Estimates index.
  877.       var estimatedIndex = Math.min(Math.floor(offset / itemHeight),
  878.                                     this.dataModel.length - 1);
  879.       var isIncrementing = this.getItemTop(estimatedIndex) < offset;
  880.  
  881.       // Searchs the correct index.
  882.       do {
  883.         var heights = this.getHeightsForIndex_(estimatedIndex);
  884.         var top = heights.top;
  885.         var height = heights.height;
  886.  
  887.         if (top <= offset && offset <= (top + height))
  888.           break;
  889.  
  890.         isIncrementing ? ++estimatedIndex : --estimatedIndex;
  891.       } while (0 < estimatedIndex && estimatedIndex < this.dataModel.length);
  892.  
  893.       return estimatedIndex;
  894.     },
  895.  
  896.     /**
  897.      * Return the number of items that occupy the range of heights between the
  898.      * top of the start item and the end offset.
  899.      * @param {number} startIndex The index of the first visible item.
  900.      * @param {number} endOffset The y offset in pixels of the end of the list.
  901.      * @return {number} The number of list items visible.
  902.      * @private
  903.      */
  904.     countItemsInRange_: function(startIndex, endOffset) {
  905.       var endIndex = this.getIndexForListOffset_(endOffset);
  906.       return endIndex - startIndex + 1;
  907.     },
  908.  
  909.     /**
  910.      * Calculates the number of items fitting in the given viewport.
  911.      * @param {number} scrollTop The scroll top position.
  912.      * @param {number} clientHeight The height of viewport.
  913.      * @return {{first: number, length: number, last: number}} The index of
  914.      *     first item in view port, The number of items, The item past the last.
  915.      */
  916.     getItemsInViewPort: function(scrollTop, clientHeight) {
  917.       if (this.autoExpands_) {
  918.         return {
  919.           first: 0,
  920.           length: this.dataModel.length,
  921.           last: this.dataModel.length};
  922.       } else {
  923.         var firstIndex = this.getIndexForListOffset_(scrollTop);
  924.         var lastIndex = this.getIndexForListOffset_(scrollTop + clientHeight);
  925.  
  926.         return {
  927.           first: firstIndex,
  928.           length: lastIndex - firstIndex + 1,
  929.           last: lastIndex + 1};
  930.       }
  931.     },
  932.  
  933.     /**
  934.      * Merges list items currently existing in the list with items in the range
  935.      * [firstIndex, lastIndex). Removes or adds items if needed.
  936.      * Doesn't delete {@code this.pinnedItem_} if it is present (instead hides
  937.      * it if it is out of the range). Adds items to {@code newCachedItems}.
  938.      * @param {number} firstIndex The index of first item, inclusively.
  939.      * @param {number} lastIndex The index of last item, exclusively.
  940.      * @param {Object.<string, ListItem>} cachedItems Old items cache.
  941.      * @param {Object.<string, ListItem>} newCachedItems New items cache.
  942.      */
  943.     mergeItems: function(firstIndex, lastIndex, cachedItems, newCachedItems) {
  944.       var self = this;
  945.       var dataModel = this.dataModel;
  946.       var currentIndex = firstIndex;
  947.  
  948.       function insert() {
  949.         var dataItem = dataModel.item(currentIndex);
  950.         var newItem = cachedItems[currentIndex] || self.createItem(dataItem);
  951.         newItem.listIndex = currentIndex;
  952.         newCachedItems[currentIndex] = newItem;
  953.         self.insertBefore(newItem, item);
  954.         currentIndex++;
  955.       }
  956.  
  957.       function remove() {
  958.         var next = item.nextSibling;
  959.         if (item != self.pinnedItem_)
  960.           self.removeChild(item);
  961.         item = next;
  962.       }
  963.  
  964.       for (var item = this.beforeFiller_.nextSibling;
  965.            item != this.afterFiller_ && currentIndex < lastIndex;) {
  966.         if (!this.isItem(item)) {
  967.           item = item.nextSibling;
  968.           continue;
  969.         }
  970.  
  971.         var index = item.listIndex;
  972.         if (cachedItems[index] != item || index < currentIndex) {
  973.           remove();
  974.         } else if (index == currentIndex) {
  975.           newCachedItems[currentIndex] = item;
  976.           item = item.nextSibling;
  977.           currentIndex++;
  978.         } else {  // index > currentIndex
  979.           insert();
  980.         }
  981.       }
  982.  
  983.       while (item != this.afterFiller_) {
  984.         if (this.isItem(item))
  985.           remove();
  986.         else
  987.           item = item.nextSibling;
  988.       }
  989.  
  990.       if (this.pinnedItem_) {
  991.         var index = this.pinnedItem_.listIndex;
  992.         this.pinnedItem_.hidden = index < firstIndex || index >= lastIndex;
  993.         newCachedItems[index] = this.pinnedItem_;
  994.         if (index >= lastIndex)
  995.           item = this.pinnedItem_;  // Insert new items before this one.
  996.       }
  997.  
  998.       while (currentIndex < lastIndex)
  999.         insert();
  1000.     },
  1001.  
  1002.     /**
  1003.      * Ensures that all the item sizes in the list have been already cached.
  1004.      */
  1005.     ensureAllItemSizesInCache: function() {
  1006.       var measuringIndexes = [];
  1007.       var isElementAppended = [];
  1008.       for (var y = 0; y < this.dataModel.length; y++) {
  1009.         if (!this.cachedItemHeights_[y]) {
  1010.           measuringIndexes.push(y);
  1011.           isElementAppended.push(false);
  1012.         }
  1013.       }
  1014.  
  1015.       var measuringItems = [];
  1016.       // Adds temporary elements.
  1017.       for (var y = 0; y < measuringIndexes.length; y++) {
  1018.         var index = measuringIndexes[y];
  1019.         var dataItem = this.dataModel.item(index);
  1020.         var listItem = this.cachedItems_[index] || this.createItem(dataItem);
  1021.         listItem.listIndex = index;
  1022.  
  1023.         // If |listItems| is not on the list, apppends it to the list and sets
  1024.         // the flag.
  1025.         if (!listItem.parentNode) {
  1026.           this.appendChild(listItem);
  1027.           isElementAppended[y] = true;
  1028.         }
  1029.  
  1030.         this.cachedItems_[index] = listItem;
  1031.         measuringItems.push(listItem);
  1032.       }
  1033.  
  1034.       // All mesurings must be placed after adding all the elements, to prevent
  1035.       // performance reducing.
  1036.       for (var y = 0; y < measuringIndexes.length; y++) {
  1037.         var index = measuringIndexes[y];
  1038.         this.cachedItemHeights_[index] =
  1039.             this.measureItemHeight_(measuringItems[y]);
  1040.       }
  1041.  
  1042.       // Removes all the temprary elements.
  1043.       for (var y = 0; y < measuringIndexes.length; y++) {
  1044.         // If the list item has been appended above, removes it.
  1045.         if (isElementAppended[y])
  1046.           this.removeChild(measuringItems[y]);
  1047.       }
  1048.     },
  1049.  
  1050.     /**
  1051.      * Returns the height of after filler in the list.
  1052.      * @param {number} lastIndex The index of item past the last in viewport.
  1053.      * @return {number} The height of after filler.
  1054.      */
  1055.     getAfterFillerHeight: function(lastIndex) {
  1056.       if (this.fixedHeight_) {
  1057.         var itemHeight = this.getDefaultItemHeight_();
  1058.         return (this.dataModel.length - lastIndex) * itemHeight;
  1059.       }
  1060.  
  1061.       var height = 0;
  1062.       for (var i = lastIndex; i < this.dataModel.length; i++)
  1063.         height += this.getItemHeightByIndex_(i);
  1064.       return height;
  1065.     },
  1066.  
  1067.     /**
  1068.      * Redraws the viewport.
  1069.      */
  1070.     redraw: function() {
  1071.       if (this.batchCount_ != 0)
  1072.         return;
  1073.  
  1074.       var dataModel = this.dataModel;
  1075.       if (!dataModel || !this.autoExpands_ && this.clientHeight == 0) {
  1076.         this.cachedItems_ = {};
  1077.         this.firstIndex_ = 0;
  1078.         this.lastIndex_ = 0;
  1079.         this.remainingSpace_ = this.clientHeight != 0;
  1080.         this.mergeItems(0, 0, {}, {});
  1081.         return;
  1082.       }
  1083.  
  1084.       // Save the previous positions before any manipulation of elements.
  1085.       var scrollTop = this.scrollTop;
  1086.       var clientHeight = this.clientHeight;
  1087.  
  1088.       // Store all the item sizes into the cache in advance, to prevent
  1089.       // interleave measuring with mutating dom.
  1090.       if (!this.fixedHeight_)
  1091.         this.ensureAllItemSizesInCache();
  1092.  
  1093.       // We cache the list items since creating the DOM nodes is the most
  1094.       // expensive part of redrawing.
  1095.       var cachedItems = this.cachedItems_ || {};
  1096.       var newCachedItems = {};
  1097.  
  1098.       var autoExpands = this.autoExpands_;
  1099.  
  1100.       var itemsInViewPort = this.getItemsInViewPort(scrollTop, clientHeight);
  1101.       // Draws the hidden rows just above/below the viewport to prevent
  1102.       // flashing in scroll.
  1103.       var firstIndex = Math.max(0, Math.min(dataModel.length - 1,
  1104.                                             itemsInViewPort.first - 1));
  1105.       var lastIndex = Math.min(itemsInViewPort.last + 1, dataModel.length);
  1106.  
  1107.       var beforeFillerHeight =
  1108.           this.autoExpands ? 0 : this.getItemTop(firstIndex);
  1109.       var afterFillerHeight =
  1110.           this.autoExpands ? 0 : this.getAfterFillerHeight(lastIndex);
  1111.  
  1112.       this.beforeFiller_.style.height = beforeFillerHeight + 'px';
  1113.  
  1114.       var sm = this.selectionModel;
  1115.       var leadIndex = sm.leadIndex;
  1116.  
  1117.       if (this.pinnedItem_ &&
  1118.           this.pinnedItem_ != cachedItems[leadIndex]) {
  1119.         if (this.pinnedItem_.hidden)
  1120.           this.removeChild(this.pinnedItem_);
  1121.         this.pinnedItem_ = undefined;
  1122.       }
  1123.  
  1124.       this.mergeItems(firstIndex, lastIndex, cachedItems, newCachedItems);
  1125.  
  1126.       if (!this.pinnedItem_ && newCachedItems[leadIndex] &&
  1127.           newCachedItems[leadIndex].parentNode == this) {
  1128.         this.pinnedItem_ = newCachedItems[leadIndex];
  1129.       }
  1130.  
  1131.       this.afterFiller_.style.height = afterFillerHeight + 'px';
  1132.  
  1133.       // We don't set the lead or selected properties until after adding all
  1134.       // items, in case they force relayout in response to these events.
  1135.       var listItem = null;
  1136.       if (leadIndex != -1 && newCachedItems[leadIndex])
  1137.         newCachedItems[leadIndex].lead = true;
  1138.       for (var y = firstIndex; y < lastIndex; y++) {
  1139.         if (sm.getIndexSelected(y))
  1140.           newCachedItems[y].selected = true;
  1141.         else if (y != leadIndex)
  1142.           listItem = newCachedItems[y];
  1143.       }
  1144.  
  1145.       this.firstIndex_ = firstIndex;
  1146.       this.lastIndex_ = lastIndex;
  1147.  
  1148.       this.remainingSpace_ = itemsInViewPort.last > dataModel.length;
  1149.       this.cachedItems_ = newCachedItems;
  1150.  
  1151.       // Mesurings must be placed after adding all the elements, to prevent
  1152.       // performance reducing.
  1153.       if (!this.fixedHeight_) {
  1154.         for (var y = firstIndex; y < lastIndex; y++)
  1155.           this.cachedItemHeights_[y] =
  1156.               this.measureItemHeight_(newCachedItems[y]);
  1157.       }
  1158.  
  1159.       // Measure again in case the item height has changed due to a page zoom.
  1160.       //
  1161.       // The measure above is only done the first time but this measure is done
  1162.       // after every redraw. It is done in a timeout so it will not trigger
  1163.       // a reflow (which made the redraw speed 3 times slower on my system).
  1164.       // By using a timeout the measuring will happen later when there is no
  1165.       // need for a reflow.
  1166.       if (listItem && this.fixedHeight_) {
  1167.         var list = this;
  1168.         window.setTimeout(function() {
  1169.           if (listItem.parentNode == list) {
  1170.             list.measured_ = list.measureItem(listItem);
  1171.           }
  1172.         });
  1173.       }
  1174.     },
  1175.  
  1176.     /**
  1177.      * Restore the lead item that is present in the list but may be updated
  1178.      * in the data model (supposed to be used inside a batch update). Usually
  1179.      * such an item would be recreated in the redraw method. If reinsertion
  1180.      * is undesirable (for instance to prevent losing focus) the item may be
  1181.      * updated and restored. Assumed the listItem relates to the same data item
  1182.      * as the lead item in the begin of the batch update.
  1183.      *
  1184.      * @param {ListItem} leadItem Already existing lead item.
  1185.      */
  1186.     restoreLeadItem: function(leadItem) {
  1187.       delete this.cachedItems_[leadItem.listIndex];
  1188.  
  1189.       leadItem.listIndex = this.selectionModel.leadIndex;
  1190.       this.pinnedItem_ = this.cachedItems_[leadItem.listIndex] = leadItem;
  1191.     },
  1192.  
  1193.     /**
  1194.      * Invalidates list by removing cached items.
  1195.      */
  1196.     invalidate: function() {
  1197.       this.cachedItems_ = {};
  1198.       this.cachedItemSized_ = {};
  1199.     },
  1200.  
  1201.     /**
  1202.      * Redraws a single item.
  1203.      * @param {number} index The row index to redraw.
  1204.      */
  1205.     redrawItem: function(index) {
  1206.       if (index >= this.firstIndex_ &&
  1207.           (index < this.lastIndex_ || this.remainingSpace_)) {
  1208.         delete this.cachedItems_[index];
  1209.         this.redraw();
  1210.       }
  1211.     },
  1212.  
  1213.     /**
  1214.      * Called when a list item is activated, currently only by a double click
  1215.      * event.
  1216.      * @param {number} index The index of the activated item.
  1217.      */
  1218.     activateItemAtIndex: function(index) {
  1219.     },
  1220.  
  1221.     /**
  1222.      * Returns a ListItem for the leadIndex. If the item isn't present in the
  1223.      * list creates it and inserts to the list (may be invisible if it's out of
  1224.      * the visible range).
  1225.      *
  1226.      * Item returned from this method won't be removed until it remains a lead
  1227.      * item or til the data model changes (unlike other items that could be
  1228.      * removed when they go out of the visible range).
  1229.      *
  1230.      * @return {cr.ui.ListItem} The lead item for the list.
  1231.      */
  1232.     ensureLeadItemExists: function() {
  1233.       var index = this.selectionModel.leadIndex;
  1234.       if (index < 0)
  1235.         return null;
  1236.       var cachedItems = this.cachedItems_ || {};
  1237.  
  1238.       var item = cachedItems[index] ||
  1239.                  this.createItem(this.dataModel.item(index));
  1240.       if (this.pinnedItem_ != item && this.pinnedItem_ &&
  1241.           this.pinnedItem_.hidden) {
  1242.         this.removeChild(this.pinnedItem_);
  1243.       }
  1244.       this.pinnedItem_ = item;
  1245.       cachedItems[index] = item;
  1246.       item.listIndex = index;
  1247.       if (item.parentNode == this)
  1248.         return item;
  1249.  
  1250.       if (this.batchCount_ != 0)
  1251.         item.hidden = true;
  1252.  
  1253.       // Item will get to the right place in redraw. Choose place to insert
  1254.       // reducing items reinsertion.
  1255.       if (index <= this.firstIndex_)
  1256.         this.insertBefore(item, this.beforeFiller_.nextSibling);
  1257.       else
  1258.         this.insertBefore(item, this.afterFiller_);
  1259.       this.redraw();
  1260.       return item;
  1261.     },
  1262.   };
  1263.  
  1264.   cr.defineProperty(List, 'disabled', cr.PropertyKind.BOOL_ATTR);
  1265.  
  1266.   /**
  1267.    * Whether the list or one of its descendents has focus. This is necessary
  1268.    * because list items can contain controls that can be focused, and for some
  1269.    * purposes (e.g., styling), the list can still be conceptually focused at
  1270.    * that point even though it doesn't actually have the page focus.
  1271.    */
  1272.   cr.defineProperty(List, 'hasElementFocus', cr.PropertyKind.BOOL_ATTR);
  1273.  
  1274.   return {
  1275.     List: List
  1276.   };
  1277. });
  1278.